package com.maxmlr.framework.context.support;

import com.google.common.collect.Lists;
import com.maxmlr.framework.beans.BeanDefinition;
import com.maxmlr.framework.util.BeansUtil;
import lombok.Getter;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.Properties;

/**
 * @ClassName BeanDefinitionReader
 * @Description TODO
 * @Author maxiao
 * @Date 2020/3/13 下午4:43
 * @Version V1.0
 */
@Getter
public class BeanDefinitionReader {

    private Properties properties = new Properties();

    private List<String> registyBeanClasses = Lists.newArrayList();

    //在配置文件中，用来获取自动扫描的包名的key
    private final String SCAN_PACKAGE = "scanPackage";

    public BeanDefinitionReader(String... configLocations) {
        ClassLoader classLoader = this.getClass().getClassLoader();

        for (String str : configLocations) {
            InputStream is = classLoader.getResourceAsStream(str.replace("classpath:", ""));
            try {
                properties.load(is);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        doScanner(classLoader, properties.getProperty(SCAN_PACKAGE));
    }

    public List<String> loadBeanDefinitions() {
        return this.registyBeanClasses;
    }

    public BeanDefinition registerBean(String className) {
        BeanDefinition beanDefinition = new BeanDefinition();
//        beanDefinition.setParentName();
        beanDefinition.setBeanClassName(className);
        beanDefinition.setFactoryBeanName(BeansUtil.lowerFirstCase(className.substring(className.lastIndexOf(".") + 1)));
//        beanDefinition.setFactoryMethodName();
        return beanDefinition;
    }


    //递归扫描所有的相关联的class，并且保存到一个List中
    private void doScanner(ClassLoader classLoader, String packageName) {

        String a = packageName.replaceAll("\\.", "/");

        URL url = classLoader.getResource(a);

        File classDir = new File(url.getFile());

        for (File file : classDir.listFiles()) {
            if (file.isDirectory()) {
                doScanner(classLoader, packageName + "." + file.getName());
            } else {
                registyBeanClasses.add(packageName + "." + file.getName().replace(".class", ""));
            }
        }


    }

    public String getProperty(String name) {
        return properties.getProperty(name);
    }
}
